package me.tonywang.common.util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


public class FileUtils {

    public FileUtils() {
    }

    /**
     * Check if a file exits.
     *
     * @param fileName The name of the file to check.
     * @return true if file exists.
     */
    public static boolean fileExists(String fileName) {
        File file = new File(fileName);
        return file.exists();
    }

    public static void newFile(String path) throws IOException {
        (new File(path)).createNewFile();
    }

    public static void newFile(String path, String content) throws IOException {
        File myfile = new File(path);
        if (!myfile.exists())
            myfile.createNewFile();
        FileWriter fw = new FileWriter(myfile);
        PrintWriter pw = new PrintWriter(fw);
        pw.println(content);
        fw.close();
    }

    public static void writeFile(String filePath, String content, boolean append)
            throws IOException {
        File myfile = new File(filePath);
        if (!append) {
            myfile.delete();
            myfile.createNewFile();
        }
        FileWriter fw = new FileWriter(filePath, true);
        fw.write(content);
        fw.close();
    }

    public static String readFile(String path) throws IOException {
        FileReader fr = new FileReader(path);
        File myfile = new File(path);
        int fileLen = (int) myfile.length();
        char buf[] = new char[fileLen];
        int len = fr.read(buf);
        String msg = new String(buf, 0, len);
        fr.close();
        return msg;
    }

    public static void delFile(String path) throws IOException {
        File myfile = new File(path);
        if (!myfile.isDirectory())
            myfile.delete();
    }

    public static List readFileByLine(String path) throws IOException {
        FileReader fr = new FileReader(path);
        BufferedReader br = new BufferedReader(fr);
        List list = new ArrayList();
        for (; br.readLine() != null; list.add(br.readLine()))
            ;
        br.close();
        fr.close();
        return list;
    }

    public static String readFileByUTF8(String path) throws IOException {
        String content = "";
        File f = new File(path);
        InputStreamReader read = new InputStreamReader(new FileInputStream(f),
                "UTF-8");
        BufferedReader reader = new BufferedReader(read);
        String line;
        while ((line = reader.readLine()) != null)
            content = (new StringBuilder(String.valueOf(content))).append(line)
                    .append("\n").toString();
        return content;
    }

    public static void saveFileByUTF8(String path, String content)
            throws IOException {
        File myfile = new File(path);
        myfile.delete();
        myfile.createNewFile();
        FileOutputStream fos = new FileOutputStream(myfile.getAbsoluteFile());
        Writer w = new OutputStreamWriter(fos, "UTF-8");
        w.write(content);
        w.close();
        fos.close();
    }

    public static void newFolder(String path) throws IOException {
        File mydir = new File(path);
        if (!mydir.exists())
            mydir.mkdirs();
    }

    public static InputStream string2stream(String srcStr) {
        InputStream is = null;
        if (!srcStr.trim().equals("")) {
            String str = srcStr;
            is = new ByteArrayInputStream(str.getBytes());
        }
        return is;
    }

    public static String stream2string(InputStream srcStream)
            throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(srcStream));
        StringBuffer buf = new StringBuffer();
        for (String line = ""; (line = br.readLine()) != null; )
            buf.append((new StringBuilder(String.valueOf(line))).append("\n")
                    .toString());

        return buf.toString();
    }

    public static InputStream getStreamInFile(String path) throws IOException {
        File myfile = new File(path);
        InputStream is = new FileInputStream(myfile);
        return is;
    }

    /**
     * 创建临时文件
     *
     * @param inputStream
     * @param name        文件名
     * @param ext         扩展名
     * @return
     * @throws IOException
     */
    public static File createTmpFile(InputStream inputStream, String name,
                                     String ext) throws IOException {
        FileOutputStream fos = null;
        try {
            File tmpFile = File.createTempFile(name, '.' + (ext == null ? "tmp" : "txt"));
//			tmpFile.deleteOnExit();
            fos = new FileOutputStream(tmpFile);
            int read = 0;
            byte[] bytes = new byte[1024 * 100];
            while ((read = inputStream.read(bytes)) != -1) {
                fos.write(bytes, 0, read);
            }
            fos.flush();
            return tmpFile;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 创建临时文件
     *
     * @param inputStream
     * @param filename
     * @throws IOException
     */
    public static File createTmpFile(InputStream inputStream, String filename) throws IOException {
        String ext = getExtension(filename, "");
        return createTmpFile(inputStream, newFileName(filename), ext);
    }

    /**
     * @param file
     * @throws Exception
     */
    public static void createFile(String file) {
        File f = new File(file);
        if (f.exists()) {
            // DO NOTHING
        } else {
            f.getParentFile().mkdirs();
            try {
                f.createNewFile();
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage());
            }
        }
    }

    /**
     * UUID重命名文件名，避免中文问题及磁盘文件重名等问题
     *
     * @param originalFilename
     * @return
     */
    public static String newFileName(String originalFilename) {
        String ext = getExtension(originalFilename, "");
        return UUID.randomUUID().toString() + "." + ext;
    }

    /**
     * @param originalFilename
     * @return
     */
    public static String newFileNameWithDate(String originalFilename) {
        String ext = getExtension(originalFilename, "");
        return originalFilename.substring(0, originalFilename.lastIndexOf('.')) + DateUtils.thisDate() + "." + ext;
    }

    /**
     * @param originalFilename
     * @return
     */
    public static String newFileNameWithDateTime(String originalFilename) {
        String ext = getExtension(originalFilename, "");
        return originalFilename.substring(0, originalFilename.lastIndexOf('.')) + DateUtils.getCurrentTime() + "." + ext;
    }

    /**
     * @param filename
     * @param defExt
     * @return
     */
    public static String getExtension(String filename, String defExt) {
        if ((filename != null) && (filename.length() > 0)) {
            int i = filename.lastIndexOf('.');
            if ((i > -1) && (i < (filename.length() - 1))) {
                return filename.substring(i + 1);
            }
        }
        return defExt;
    }

}
